;(function(){
		function MyMap(data){
			var _this=this;
			_this.mapareaData=[];
			_this.labelsDate=[];
			this.param={
				id:"",
				message:'',
				map:'',
				styleOPtions:{
								selected:true,
								strokeWeight:2, //设置多边形边线线粗							   
							   strokeOpacity:1, //设置多边形边线透明度0-1
							   StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashed
							   strokeColor:["#008cff","#26c4ca",'#3bac2a','#8c81f5','#ff7ea0','#ff7ea0','#fdda19','#5a9f0f','#ff7e00'], //设置多边形边线颜色
							   fillColor:["#008cff","#26c4ca",'#3bac2a','#8c81f5','#ff7ea0','#ff7ea0','#fdda19','#5a9f0f','#ff7e00']
							}
			};
			this.areaData={
				leve:1,
				areaDataList:[{
					name:'琼海市',
					position:'',
					grid_id:null,
					grid_level:2,
				}],
				select_id:null,
			}
			this.mapleve=10;
			this.Cluster=[];
			this._markerClusterer=null;
			this.init(data);
			
		}
		MyMap.prototype={
			init:function(data){
				this.initData(data);
				this.createMap();
			},
			//数据初始化
			initData:function (data) {
				//debugger;
				Object.assign(this.param,data);
			},
			//创建地图
			createMap:function(){
				var _this=this;
				// 百度地图API功能
				_this.map = new BMap.Map(_this.param.id);    // 创建Map实例
				_this.map.centerAndZoom(new BMap.Point(109.717426,19.27341),_this.mapleve);  // 初始化地图,设置中心点坐标和地图级别
				//添加地图类型控件
				_this.map.addControl(new BMap.MapTypeControl({
					mapTypes:[
						BMAP_NORMAL_MAP,
						BMAP_HYBRID_MAP
					]}));	  
					//_this.map.setCurrentCity("海口市");          // 设置地图显示的城市 此项是必须设置的
			 	    _this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
			},
			//绘制网格
			drawGrid:function(data,callback1,callback2){	
				var _this=this;
				var callback1=callback1||Function;
				var callback2=callback2||Function;
				this.mapareaData=[];
				_this.labelsDate=[]
			
				_this.areaData=data
				//_this.clearoverlays();
				_this.clearalloverlays();
				if(data.leve<3){
					var datalist=[];
					var _datalist=data.areaDataList;
					var bdary = new BMap.Boundary();
					for(var i=0;i<_datalist.length;i++){
						this.getBoundary(_datalist[i].name,_datalist[i].grid_id,_datalist[i].grid_level,callback1,callback2);
					}
				}else{
					_this.areaData.areaDataList=data.areaDataList;
					this.getGrid(callback1,callback2);
				}
				
			},
			//网格绘制
			getGrid:function(callback1,callback2){
				var _this=this;
				var callback1=callback1||Function;
				var callback2=callback2||Function;
				var namearr=[];
				var levearr=[];
				var grid_idarr=[];
				//debugger;
				var plys=[];
				var labels=[];
				var _areaData=_this.areaData.areaDataList;
				//debugger;
				for(var i=0;i<_areaData.length;i++){
					var _color=_this.getColor(i)
					plys[i]= new BMap.Polygon(_areaData[i].position,{
						fillColor:_color,
						strokeWeight:2, //设置多边形边线线粗							   
						strokeOpacity:1, //设置多边形边线透明度0-1
						StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashed
						strokeColor:_color, //设置多边形边线颜色,
						fillOpacity:.1
						
					})
					
					_this.map.addOverlay(plys[i]);  //添加覆盖物
					
					namearr.push(_areaData[i].name);
					levearr.push(_areaData[i].grid_level);
					grid_idarr.push(_areaData[i].grid_id);
					
					plys[i].addEventListener("click",function(i){
						return function(){
							callback1(namearr[i],levearr[i],grid_idarr[i]);
						}
					}(i));
					plys[i].grid_id=_areaData[i].grid_id;
					_this.mapareaData.push(plys[i]);
					
					var poin=_this.drawText02(_areaData[i].position)
					var point = new BMap.Point(poin.lng,poin.lat); 
					labels[i] = new BMap.Label(_areaData[i].name,{position:point,offset:new BMap.Size(20,-10)});
					labels[i].setStyle({
						fontSize : "12px",
						height : "20px",
						lineHeight : "20px",
						borderColor:"#52affc",
						background:"#52affc",
						color:"#fff",
						padding:"0 10px",
						display:"none",
					})
					_this.map.addOverlay(labels[i]);
					_this.labelsDate.push(labels[i]);
					plys[i].addEventListener("mouseover",function(i){
						return function(){
							labels[i].setStyle({
								display:"block"
							})
							callback2(0,_areaData[i].grid_id);
						}
					}(i));
					plys[i].addEventListener("mouseout",function(i){
						return function(){
							labels[i].setStyle({
								display:"none"
							})
							callback2(1,_areaData[i].grid_id);
						}
					}(i));


					plys[i].disableMassClear();

					//_this.drawText(_this.areaData.areaDataList[i].name,_this.areaData.areaDataList[i].position);
					
				}
				
				var _poin=_this.drawText02(_areaData[_areaData.length-1].position);
				var _point02 = new BMap.Point(_poin.lng,_poin.lat); 
				
				_this.map.centerAndZoom(_point02,_this.mapleve+(_this.areaData.leve -1)/2)
				//_this.map.centerAndZoom(new BMap.Point(109.717426,19.27341),_this.mapleve+_this.areaData.leve-1)
				
				
			}
			,
			//行政区域绘制
			getBoundary:function (name,grid_id,grid_level,callback1,callback2){ 
				var _this=this;
				var bdary = new BMap.Boundary();
				//var name = document.getElementById("districtName").value;
				var plys=[];
				var labels=[];
				bdary.get(name, function(rs){       //获取行政区域
					//清除地图覆盖物  
					var count = rs.boundaries.length; //行政区域的点有多少个
					
					for(var i = 0; i < count; i++){
					  //console.log(rs.boundaries[i],i);
					  if(grid_id){
						var _color=_this.getColor(i);
						plys[i]= new BMap.Polygon(rs.boundaries[i],{
							fillColor:_color,
							strokeWeight:2, //设置多边形边线线粗							   
							strokeOpacity:1, //设置多边形边线透明度0-1
							StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashed
							strokeColor:_color, //设置多边形边线颜色,
							fillOpacity:.1
						}); //建立多边形覆盖物
						var poin=_this.drawText02(rs.boundaries[i])
						var point = new BMap.Point(poin.lng,poin.lat);
						plys[i].addEventListener("click", function(event){
							//_this.map.centerAndZoom(point,_this.mapleve+_this.areaData.leve-1)
							callback1(name,grid_level,grid_id);
						});
						labels[i] = new BMap.Label('<span id="123	">'+name+'</span>',{position:point,offset:new BMap.Size(20,-10)});
						labels[i].setStyle({
							fontSize : "12px",
							height : "20px",
							lineHeight : "20px",
							borderColor:"#52affc",
							background:"#52affc",
							color:"#fff",
							padding:"0 10px",
							display:"none",
						})
						_this.map.addOverlay(labels[i]);
						
						plys[i].addEventListener("mouseover",function(i){
							return function(){
								labels[i].setStyle({
									display:'block',
								})
								callback2(0,grid_id)
							}
						}(i));
						plys[i].addEventListener("mouseout",function(i){
							return function(){
								labels[i].setStyle({
									display:"none"
								})
								callback2(1,grid_id)
							}
						}(i));
						plys[i].grid_id=grid_id;
						_this.mapareaData.push(plys[i]);
						_this.labelsDate.push(labels[i]);	

					  }else{
						plys[i] = new BMap.Polygon(rs.boundaries[i],{
							strokeWeight:1, //设置多边形边线线粗							   
							strokeOpacity:1, //设置多边形边线透明度0-1
							StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashed
							strokeColor: "#aaa", //设置多边形边线颜色
							fillColor:"#fff",
							fillOpacity:.3
						 }); //建立多边形覆盖物
					}
					
						//debugger;
						_this.map.addOverlay(plys[i]);  
						plys[i].disableMassClear(); 
						
						
					} 
					var _poin=_this.drawText02(rs.boundaries[count-1]);
					var _point02 = new BMap.Point(_poin.lng,_poin.lat); 
					//_this.map.centerAndZoom(_point02,_this.mapleve+_this.areaData.leve-1)
					//_this.map.centerAndZoom(new BMap.Point(109.717426,19.27341),_this.mapleve+_this.areaData.leve-1)
					
					
				});   
			},
			//修改网格模块的颜色值
			changeColorGird:function(grid_id){
				var _this=this;
				var _arr=_this.mapareaData;
				if(_arr.length==0) return false;
				_arr.map(function(itme,index){
					if(itme.grid_id==grid_id){
						itme.setFillOpacity(".3");
						_this.labelsDate[index].setStyle({
							display:"block"
						})
						
					}else{
						var _color=_this.getColor(index);
						itme.setFillOpacity(".1");
						_this.labelsDate[index].setStyle({
							display:"none"
						})
						
					}
				})


			},
			//随机获取颜色
			getColor:function(i){
				var _this=this;
				return _this.param.styleOPtions.strokeColor[i%_this.param.styleOPtions.strokeColor.length];
				//return _this.param.styleOPtions.fillColor[parseInt(4*Math.random())]
			},
			//绘制区域
			addGrid:function(data,callback1,callback2){
				var  _this=this;
				_this.areaData=data;
				var  overlay=[];
				for(var i = 0; i <_this.areaData.length; i++){
					var _color=_this.getColor(i);
					overlay[i] = new BMap.Polygon(_this.areaData[i].position,{
						fillColor:_color,
						strokeWeight:2, //设置多边形边线线粗							   
						strokeOpacity:1, //设置多边形边线透明度0-1
						StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashed
						strokeColor:_color, //设置多边形边线颜色
						
					}); //建立多边形覆盖物
					_this.map.addOverlay(overlay[i]);  //添加覆盖物
					_this.map.setViewport(overlay[i].getPath());    //调整视野
					overlay[i].addEventListener("click",function(i){
                    return function(){
                        callback1(i);
	                    }
	                }(i));
	                overlay[i].addEventListener("dblclick",function(i){
	                    return function(){
	                        callback2(i);
	                    }
					}(i));


					overlay[i].addEventListener("mouseover",function(i){
						return function(){
							
							}
						}(i));
						overlay[i].addEventListener("mouseout",function(i){
							return function(){
								
							}
						}(i));
					
					
				} 
				 
			},
			//绘制文本2
			drawText02:function(_position){
				var _this=this;
				if(!_position) return false;
				var  _data=_position.split(";");
				var  _dataarr=[];
				_data.map(function(itme,index){
					var arr=itme.split(",");
					_dataarr.push({
						lng:arr[0].replace(/^\s+|\s+$/g,""),
						lat:arr[1].replace(/^\s+|\s+$/g,""),
					})
				})
				var jwd= this.getAreaCenter(_dataarr);
					
				return jwd;
			},
			//绘制文本；
			drawText:function(name,_position){
				var _this=this;
				var  _data=_position.split(";");
				var  _dataarr=[];
				_data.map(function(itme,index){
					var arr=itme.split(",");
					_dataarr.push({
						lng:arr[0].replace(/^\s+|\s+$/g,""),
						lat:arr[1].replace(/^\s+|\s+$/g,""),
					})
				})
				var jwd= this.getAreaCenter(_dataarr);
				var point = new BMap.Point(jwd.lng,jwd.lat);
				var opts = {
					position : point,    // 指定文本标注所在的地理位置
					offset   : new BMap.Size(-30, -30)    //设置文本偏移量
				  }
				  var label = new BMap.Label(name, opts);  // 创建文本标注对象
				  label.setTitle(name)
					  label.setStyle({
						   color : "#4892ff",
						   fontSize : "14px",
						   height : "20px",
						   lineHeight : "20px",
						   fontFamily:"微软雅黑",
						   borderColor:'#4892ff'
					   });
				  _this.map.addOverlay(label);  
				  label.disableMassClear(); 
				  _this.map.centerAndZoom(point,(_this.mapleve+_this.areaData.leve-1)/2) 
				    
			},
			//添加聚合
			markerClusterer:function(obj,fun){
				//聚合的引入下面两个js
				// <script type="text/javascript" src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script>
				// <script type="text/javascript" src="http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script>
				
				var _this=this;
				if(obj.length==0) return false;
				var markers = [];
				var pt = null;
				var _ico=require('./../images/qsd0.png');
				for(var i=0;i<obj.length;i++){
					// 将标注添加到地图中
					if(_this.checkRg(obj[i].lng)&&_this.checkLong(obj[i].lat)){
						pt = new BMap.Point(obj[i].lng,obj[i].lat);
						markers.push(new BMap.Marker(pt,{icon:new BMap.Icon(_ico, new BMap.Size(16,16))}));
					}
				}
				//最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
				_this._markerClusterer = new BMapLib.MarkerClusterer(_this.map, {markers:markers});
			},
			
			//校验经度
			checkRg:function(lng){
				var  longrg= /^(\-|\+)?((1[0-7]\d)|([1-9]\d)|(\d))\.\d{5}(\d)+$/;
				if(!longrg.test(lng)){
					return '经度整数部分为0-18';
				}
				return true;
			},
			//纬度
			checkLong:function(lat){
				var latreg = /^(\-|\+)?(([1-8]\d)|(\d))\.\d{5}(\d)+$/;
				
				if(!latreg.test(lat)){ 
					return '纬度整数部分为0-90'
				}
				return true;
			}
			,
			//添加ico
			addIco:function(obj,fun){
				//debugger;
				//网格钻取，清除所有 ，单位重新绘制下就行了
				var _this=this;
				_this.clearoverlays();
				_this.clearClusterer();
				if(obj.length==0) return false;
				var icons=[];
				//单位
				icons["unit_nor0"]="unit_nor0.png";
				icons["unit_nor1"]="unit_nor1.png";
				icons["unit_nor2"]="unit_nor2.png";
				icons["unit_impor0"]="unit_impor0.png";
				icons["unit_impor1"]="unit_impor1.png";
				icons["unit_impor2"]="unit_impor2.png";
				icons["unit_small0"]="unit_small0.png";
				icons["unit_small1"]="unit_small1.png";
				icons["unit_small2"]="unit_small2.png";
				//消防公共设施
				icons["swxhs0"]="swxhs0.png";
				icons["swxhs1"]="swxhs1.png";
				icons["swxhs2"]="swxhs2.png";
				icons["xfsh0"]="xfsh0.png";
				icons["xfsh1"]="xfsh1.png";
				icons["xfsh2"]="xfsh2.png";
				icons["qsd0"]="qsd0.png";
				icons["qsd1"]="qsd1.png";
				icons["qsd2"]="qsd2.png";
				//消防站
				icons["qyxfz0"]="qyxfz0.png";
				icons["zdxfz0"]="zdxfz0.png";


				var _position=[];
				var _ico='';
				var plys=[];
				var labels=[]
				for(var i=0;i<obj.length;i++){
					// 将标注添加到地图中
					if(_this.checkRg(obj[i].lng)&&_this.checkLong(obj[i].lat)){
						_position.push({
						lng:obj[i].lng,
						lat: obj[i].lat
					})
					if(obj[0].hasOwnProperty('status')){
						var _ico=_this.getIco(obj,i,icons,'status');
					}else if(obj[0].hasOwnProperty('score')){
						var _ico=_this.getIco(obj,i,icons,'score');
					}else{
						var _ico=_this.getIco(obj,i,icons,'small');
					}
					
					plys[i]=new BMap.Marker(new BMap.Point(obj[i].lng, obj[i].lat),{icon:new BMap.Icon(_ico, new BMap.Size(18,18))})
					//_this.map.addOverlay(plys[i]);
					
					plys[i].addEventListener("click",function(i){
						return function(){
							fun(obj[i].id)
						}
					}(i));
					plys[i].addEventListener("mouseover",function(i){
						return function(){
							labels[i] = new BMap.Label('<span class="map-label">'+obj[i].name+'</span>',{offset:new BMap.Size(20,-20)});
							labels[i].setStyle({
								fontSize : "12px",
								height : "20px",
								lineHeight : "20px",
								border:"none",
								background:"none",
								color:"#333",
							})
							plys[i].setLabel(labels[i])
						}
					}(i));
					plys[i].addEventListener("mouseout",function(i){
						return function(){
							labels[i].setStyle({
								display:"none",
							})
						}
					}(i));
					}	
				} 
				_this._markerClusterer = new BMapLib.MarkerClusterer(_this.map, {markers:plys});
				_this.Cluster=plys;
				      
			},
			clearLastClusters:function(){
				var _this=this;
				for(var i = 0;i<=_this.Cluster.length; i++){
					_this.Cluster.isInCluster = false;
				}
			}, 
			getIco:function(obj,i,icons,type){
				var _ico='';
				if(type=='score'){
					if(obj[i].type==1){
						if(obj[i].score==0){
							_ico=require('./../images/'+icons["unit_impor0"]);
						}
						else if(obj[i].score>=3){
							_ico=require('./../images/'+icons["unit_impor2"]);
						}else{
							_ico=require('./../images/'+icons["unit_impor1"]);
						}
						
					}
					if(obj[i].type==2){
						if(obj[i].score==0){
							_ico=require('./../images/'+icons["unit_nor0"]);
						}
						else if(obj[i].score>=3){
							_ico=require('./../images/'+icons["unit_nor2"]);
						}else{
							_ico=require('./../images/'+icons["unit_nor1"]);
						}
						
					}
					if(obj[i].type==3){
						if(obj[i].score==0){
							_ico=require('./../images/'+icons["unit_small0"]);
						}
						else if(obj[i].score>=3){
							_ico=require('./../images/'+icons["unit_small2"]);
						}else{
							_ico=require('./../images/'+icons["unit_small1"]);
						}
						
					}
				}else if(type=='status'){
					//debugger;
					if(obj[i].type==1){
						if(obj[i].status==0){
							_ico=require('./../images/'+icons["swxhs0"]);
						}
						else{
							_ico=require('./../images/'+icons["swxhs1"]);
						}	
					}
					if(obj[i].type==2){
						if(obj[i].status==0){
							_ico=require('./../images/'+icons["xfsh0"]);
						}
						else{
							_ico=require('./../images/'+icons["xfsh1"]);
						}	
					}
					if(obj[i].type==3){
						if(obj[i].status==0){
							_ico=require('./../images/'+icons["qsd0"]);
						}
						else{
							_ico=require('./../images/'+icons["qsd1"]);
						}	
					}
				}else{
					if(obj[i].type==1){
						_ico=require('./../images/'+icons["qyxfz0"]);
					}else{
						_ico=require('./../images/'+icons["zdxfz0"]);
					}
				}
				return _ico;
			},
			//清除所有的覆盖物
	        clearalloverlays:function(){
				var _this=this;
				//debugger;
				var allOverlay = _this.map.getOverlays();
				
	            if(allOverlay.length==0){
	            	return false;
				}
	            for(var i in allOverlay){
					if(allOverlay[i].Nb=='overlay'){
						allOverlay[i].enableMassClear();
					}
	               
				}
	            _this.clearoverlays();
	        },
	         //清除覆盖物
	        clearoverlays:function(){
				var _this=this;
				_this.map.clearOverlays();
			},
			clearClusterer:function(){
				var  _this=this;
				if(_this._markerClusterer){
					_this._markerClusterer.clearMarkers(_this.Cluster);
				}
			},
	        //计算区域的中心点
         getAreaCenter: function(lnglatarr){  
           var total = lnglatarr.length;
               var X=0,Y=0,Z=0;
               $.each(lnglatarr, function(index, lnglat) {
                   var lng = lnglat.lng * Math.PI / 180;
                   var lat = lnglat.lat * Math.PI / 180;
                   var x,y,z;
                   x = Math.cos(lat) * Math.cos(lng);
                   y = Math.cos(lat) * Math.sin(lng);
                   z = Math.sin(lat);
                   X += x;
                   Y += y;
                   Z += z;
               });

               X = X/total;
               Y = Y/total;
               Z = Z/total;

               var Lng = Math.atan2(Y,X);
               var Hyp = Math.sqrt(X*X + Y*Y);
               var Lat = Math.atan2(Z,Hyp);
               return {
                   lng:Lng*180/Math.PI,
                   lat:Lat*180/Math.PI
            }
         }
		}
		window.myMap=function(data){
			return new MyMap(data);
		}
		
	})(); 